﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Agile.Service.Rbac;

using Microsoft.AspNetCore.Mvc;

namespace Web.Areas.Rbac.Controllers
{
    [Area("rbac")]
    public class MenuController : BaseController<Menu>
    {
        private readonly IMenuService _menuService;
        private readonly IMenuElementService _menuElementService;
        public MenuController(IMenuService menuService, IMenuElementService menuElementService)
        {
            _menuService = menuService;
            _menuElementService = menuElementService;
        }
        [HttpGet]
        public IActionResult GetTreeSelectJson()
        {
            var data = _menuService.GetByAll().OrderByDescending(p => p.OrderBy).ToList();
            var treeList = new List<TreeSelectModel>();
            foreach (Menu item in data)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.ID;
                treeModel.text = item.Name;
                treeModel.parentId = item.ParentID;
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeSelectJson());
        }
        [HttpGet]
        public IActionResult GetGridDataJson(string pId, Paging paging)
        {
            System.Text.StringBuilder strWhere = new System.Text.StringBuilder();
            strWhere.Append(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(pId))
            {
                strWhere.Append(" AND ParentID='" + pId + "' ");
            }
            if (!string.IsNullOrWhiteSpace(paging.keyword))
            {
                strWhere.Append(" AND Name like '%" + paging.keyword + "%' ");
            }
            paging.sqlwhere = strWhere.ToString();
            return base.GetJGridPageDataJson(paging);
        }
        [HttpPost]
        public IActionResult Collect()
        {
            string baseUrl = "";
            var menus = _menuService.GetByAll("Name NOT IN('系统结构','健康检查','图标管理') AND ParentID<>'00000000-0000-0000-0000-000000000000'");
            foreach (var menu in menus)
            {
                var uri = menu.Url.Split("/");
                if (uri.Length <= 1) continue;
                string url = baseUrl + menu.Url;
                string testContent = url.GetPageContent().GetFirstHTML();
                if (!string.IsNullOrWhiteSpace(testContent))
                {
                    // <a\b[^>]+\bid="NF-([^"]*)"[^>]*>([\s\S]*?)</a>
                    string pattern = @"<a\b[^>]+\bid=""NF-([^""]*)""[^>]*>([\s\S]*?)</a>";
                    Regex s = new Regex(pattern);
                    if (s.IsMatch(testContent))
                    {
                        foreach (Match item in s.Matches(testContent))
                        {
                            //<a id="NF-add" authorize="yes" class="btn btn-primary dropdown-text" onclick="AddBatch()"><i class="glyphicon glyphicon-plus"></i>新增</a>
                            string tempstr = item.Groups[0].Value;
                            MenuElement pageButton = new MenuElement();
                            pageButton.ModuleId = menu.ID;
                            pageButton.Name = Utils.GetChineseWord(tempstr);
                            pageButton.DomId = GetBtnInfo(tempstr, @"id=.+?""", "id=");
                            pageButton.Icon = GetBtnInfo(tempstr, @"<i\b[^>]+\bclass=.+?""", "<i").Replace("class=", "");
                            pageButton.Script = GetBtnInfo(tempstr, @"onclick=.+?""", "onclick=");
                            pageButton.Remark = "收集页面命令";
                            var flg = _menuElementService.Exist(p => p.Name == pageButton.Name && p.ModuleId == menu.ID);
                            if (!flg)
                            {
                                _menuElementService.Add(pageButton);
                            }
                        }
                    }
                }
            }
            return Success("收集页面命令成功。");
        }
        private static string GetBtnInfo(string m_outstr, string pattern, string filter = "")
        {
            string tempstr = "";
            Regex s = new Regex(pattern);
            if (s.IsMatch(m_outstr))
            {
                foreach (Match item in s.Matches(m_outstr))
                {
                    tempstr = item.Groups[0].Value;
                    tempstr = tempstr.Replace(@"""", "");
                    tempstr = tempstr.Replace(filter, "");
                    break;
                }
            }
            return tempstr;
        }
        [HttpPost]
        public override IActionResult Switch(string keyId)
        {
            _menuService.Switch(keyId);
            return Success("操作成功。");
        }
        public override IActionResult SubmitForm(Menu moduleEntity)
        {
            if (moduleEntity.ParentID == "0") moduleEntity.ParentID = Guid.Empty.ToString();
            moduleEntity.Icon = "fa fa-bars";
            return base.SubmitForm(moduleEntity);
        }
        public override IActionResult DeleteForm(string keyValue)
        {
            if (string.IsNullOrWhiteSpace(keyValue)) return Error("参数keyValue不能为空！");
            _menuService.DeleteAll(keyValue);
            return Success("删除成功。");
        }
    }
}